#include "main_page.h"
#include "ui_main_page.h"
#include <QMessageBox>
#include <QPixmap>
#include <QFile>

MainPage::MainPage(QWidget *parent)
    : QWidget(parent), ui(new Ui::MainPage)
{
    ui->setupUi(this);
    setupConnections();
    // 主页面初始化时进行一次 socket_client 连接
    DeviceConfig device_config = BoardUtils::getInstance().loadDeviceConfig("device_config.txt");
    std::string client_id = device_config.brand_code + "_" + device_config.organization + "_" + device_config.zone + "_" + device_config.sn_code;

    auto client = BoardUtils::getInstance().socketClient();
    client->close(); // 确保断开旧连接
    client->setClientId(client_id);
    if (!client->connect("8.152.4.127", 18843, client_id))
    {
        std::cerr << "主页面初始化连接服务器失败，将在后台尝试重连" << std::endl;
    }
}

void MainPage::setupConnections()
{
    connect(ui->storeBtn, &QPushButton::clicked, this, [this]() {
        CabinetCollectDialog dlg(this);
        dlg.exec();
    });

    connect(ui->pickupBtn, &QPushButton::clicked, this, [this]() {
        CabinetHalfwayDialog dlg(this);
        dlg.exec();
    });

    connect(ui->releaseBtn, &QPushButton::clicked, this, [this]() {
        CabinetReturnDialog dlg(this);
        dlg.exec();
    });

    connect(ui->longRentBtn, &QPushButton::clicked, this, [this]() {
        CabinetLongRentDialog dlg(this);
        dlg.exec();
    });

    connect(ui->adminBtn, &QPushButton::clicked, this, [this]() {
        AdminDialog dlg(this);
        dlg.exec();
    });

    // 新增：点击说明区按钮加载二维码
    connect(ui->descLabelBtn, &QPushButton::clicked, this, &MainPage::loadQrCode);
}

void MainPage::loadQrCode()
{
    QFile file("qrcode.jpg");
    if (file.exists()) {
        QPixmap pixmap("qrcode.jpg");
        ui->qrCodeLabel->setPixmap(pixmap.scaled(ui->qrCodeLabel->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation));
    } else {
        ui->qrCodeLabel->setText("二维码未生成");
    }
}